package com.keya.pull;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.keya.base.exception.BusinessException;
import com.keya.mapper.PublicParamMapper;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 公共参数管理 服务类
 * </p>
 *
 * @author hsq
 * @since 2022-08-16
 */
@Service
public class PublicParamService extends ServiceImpl<PublicParamMapper, PublicParam> {

    public PublicParam getByKey(String key) {
        return getOne(new LambdaQueryWrapper<PublicParam>()
                .eq(PublicParam::getPublicKey, key));
    }

    public void updateByKey(String key, String value) throws BusinessException {
        updateByKey(key, value, 0);
    }

    public void updateByKey(String key, String value, int status) throws BusinessException {
        PublicParam param = getByKey(key);
        if (param == null) {
            throw new BusinessException(-1, key + "不存在");
        }
//        Integer userId = Optional.ofNullable(LoginUserContext.getContext()).orElse(new JwtClaim()).getUserId();
        param.setStatus(status)
                .setPublicValue(value)
                .setUpdateTime(LocalDateTime.now())
                .setUpdateBy(1)
                .updateById();
    }

    public DatasourceViewVO getDatasourceView() {
        PublicParam param = getByKey(PublicParamKey.DATA_SOURCE_VIEW);
        if (param == null) {
            return null;
        }
        try {
            return JSON.parseObject(param.getPublicValue(), DatasourceViewVO.class);
        } catch (Exception e) {
            return null;
        }
    }

    public DatasourcePacsVO getDatasourcePacs() {
        PublicParam param = getByKey(PublicParamKey.DATA_SOURCE_PACS);
        if (param == null) {
            return null;
        }
        try {
            return JSON.parseObject(param.getPublicValue(), DatasourcePacsVO.class);
        } catch (Exception e) {
            return null;
        }
    }

    public PullStudyCronVO getPullStudy() {
        PublicParam param = getByKey(PublicParamKey.PULL_STUDY_CRON);
        if (param == null) {
            return null;
        }
        try {
            return JSON.parseObject(param.getPublicValue(), PullStudyCronVO.class);
        } catch (Exception e) {
            return null;
        }
    }
}
